﻿using FieldTools.Client.Command;
using FieldTools.Client.Model.Window;
using FieldTools.Client.Entity;
using FieldTools.Util;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Text;
using ControlzEx.Theming;
using System.Windows;

namespace FieldTools.Client.ViewModel.Window
{

    public class LoginViewModel : NotificationObject, ISingletonDependency
    {
        /// <summary>
        /// 初始构造
        /// </summary>
        public LoginViewModel()
        {
            obj.UserName = "Admin";
            obj.Password = "123456";
            GlobalParm.LoginType = 2;
            var accenColor = CacheHelper.GetCache("AccentColor");
            if (accenColor != null)
            {
                ThemeManager.Current.ChangeThemeColorScheme(Application.Current, accenColor.ToString());
            }

            var appTheme = CacheHelper.GetCache("AppTheme");
            if (appTheme != null)
            {
                ThemeManager.Current.ChangeThemeBaseColor(Application.Current, appTheme.ToString());
            }
        }

        private static string LocUserName = "Admin";
        private static string LocPassword = "123456";

        #region 实体

        /// <summary>
        /// Model对象
        /// </summary>
        private LoginModel obj = new LoginModel();

        /// <summary>
        /// 用户名
        /// </summary>
        public string? UserName
        {
            get
            {
                return obj.UserName;
            }
            set
            {
                obj.UserName = value;
                this.RaisePropertyChanged(nameof(UserName));
            }
        }

        /// <summary>
        /// 密码
        /// </summary>
        public string? Password
        {
            get
            {
                return obj.Password;
            }
            set
            {
                obj.Password = value;
                this.RaisePropertyChanged(nameof(Password));
            }
        }

        /// <summary>
        /// 登录类型
        /// </summary>
        public int LoginType
        {
            get
            {
                return GlobalParm.LoginType;
            }
            set
            {
                GlobalParm.LoginType = value;
                this.RaisePropertyChanged(nameof(LoginType));
            }
        }
        #endregion

        #region 事件
        private BaseCommand loginClick;
        /// <summary>
        /// 登录事件
        /// </summary>
        public BaseCommand LoginClick
        {
            get
            {
                if (loginClick == null)
                {
                    loginClick = new BaseCommand(new Action<object>(o =>
                    {
                        //执行登录逻辑
                        //MessageBox.Show($"点击登陆，登录信息：{obj.ToJson()}");
                        if(GlobalParm.LoginType == 1)
                        {
                            HandleLoginOnline();
                        }
                        if (GlobalParm.LoginType == 2)
                        {
                            if (obj.UserName == LocUserName && obj.Password == LocPassword)
                            {
                                WindowManager.Show("ToolsBox", null);
                                ToClose = true;
                            }
                        }
                    }));
                }
                return loginClick;
            }
        }

        private bool toClose = false;
        /// <summary>
        /// 是否要关闭窗口
        /// </summary>
        public bool ToClose
        {
            get
            {
                return toClose;
            }
            set
            {
                toClose = value;
                if (toClose)
                {
                    this.RaisePropertyChanged(nameof(ToClose));
                }
            }
        }
        #endregion

        #region 方法
        /// <summary>
        /// 登陆，请求验证服务器
        /// </summary>
        private void HandleLoginOnline()
        {
            object o = new { userName = UserName, password = Password };
            string bodyJson = o.ToJson();
            string jsonString = File.ReadAllText("appsettings.json", Encoding.GetEncoding("utf-8"));//读取文件

            JObject jobject = JObject.Parse(jsonString);//解析成json
            var webRootUrl = jobject["WebRootUrl"]?.ToString();
            var res = HttpHelper.PostData(webRootUrl+"/Base_Manage/Home/SubmitLogin", bodyJson, "application/json", null);
            if (!res.IsNullOrEmpty())
            {
                var resData = res.ToObject<ServerReturn>();
                if (resData.Success == true)
                {
                    //存储密钥到缓存，供验证使用jwtToken
                    CacheHelper.SetCache("jwtToken", resData.Data, new DateTimeOffset(DateTime.Now, TimeSpan.FromDays(1)));
                    //MessageBox.Show("登录成功");
                    WindowManager.Show("ToolsBox", null);
                    ToClose = true;
                }
                else
                {
                    MessageBox.Show("登录失败" + resData.Msg);
                }
            }

        }
        #endregion
    }
}
